const path = require('path')
const CopyPlugin = require("copy-webpack-plugin")
const HtmlPlugin = require('html-webpack-plugin')
const SRIPlugin = require('webpack-subresource-integrity')

module.exports = {
    mode: 'development',
    entry: './src/index.js',
    output: {
        filename: 'main.js',
        path: path.resolve(__dirname, 'dist'),
        crossOriginLoading: 'anonymous',
    },
    devtool: 'inline-source-map',
    devServer: {
        static: {
            directory: './dist',
        }
    },
    // WasmThemis code is generated by Emscripten to be universal.
    // It includes some references to Node.js modules for Node.js support,
    // but they are not accessible (and not used) in web browsers.
    resolve: {
        fallback: {
            crypto: false,
            fs: false,
            http: false,
            https: false,
            net: false,
            path: false,
            stream: false,
            tls: false,
            util: false,
            url: false,
            zlib: false,
        }
    },
    // I have no clue *why* this happens, and I don't care. Fix the warnings.
    // https://github.com/websockets/ws/issues/1126
    externals: {
        "bufferutil": "bufferutil",
        "utf-8-validate": "utf-8-validate",
    },
    // Bundle libthemis.wasm with the script.
    // Compute SRI hash sum of the script and inject it into HTML.
    plugins: [
        new CopyPlugin({
            patterns: [
                { from: 'node_modules/wasm-themis/src/libthemis.wasm',
                    to: '.'
                },
            ],
        }),
        new HtmlPlugin({
            filename: 'index.html',
            template: 'src/index.html',
        }),
        new SRIPlugin({
            hashFuncNames: ['sha256'],
            // webpack-subresource-integrity *really* does not like dev server.
            // https://github.com/waysact/webpack-subresource-integrity/blob/5c42f351a2070b1f3323f14bcfcb8e0b62a202b3/README.md#hot-reloading
            enabled: process.env.NODE_ENV === 'production',
        }),
    ],
    // libthemis.wasm and it's JS bundle is over 1 megabyte.
    // It's okay. Please be quiet, webpack.
    performance: {
        maxAssetSize: 2000000,
        maxEntrypointSize: 2000000,
    },
}
